<template>
  <div class="img-cropper">
    <div class="img-box">
      <img :src="imgUrl" alt="" />
    </div>
    <input
      v-show="false"
      type="file"
      id="fileInput"
      @change="handleFileChange"
      name="file"
      ref="file"
    />
    <el-dropdown style="margin-top: 10px">
      <span class="el-dropdown-link">
        标题图设置<i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item icon="el-icon-upload2">
          <label for="fileInput">
            <i aria-hidden="true">上传图片</i>
          </label>
        </el-dropdown-item>
        <el-dropdown-item
          icon="el-icon-upload2"
          @click.native="selectFromArticle"
          >从正文中选择</el-dropdown-item
        >
        <el-dropdown-item
          icon="el-icon-upload2"
          @click.native="selectFromLibrary"
          >从资源库中选择</el-dropdown-item
        >
        <el-dropdown-item icon="el-icon-circle-close" @click.native="deleteImg"
          >取消图片</el-dropdown-item
        >
      </el-dropdown-menu>
    </el-dropdown>
    <Cropper @e-emit="setImgInfo" />
    <SelectImgFromArticle :content="content" @e-emit="setSelectImgInfo" />
    <SelectImgFromLibrary @e-emit="setSelectImgInfo" />
  </div>
</template>
<script>
import { tbSysAttachmentUpload } from '@/api/http'
import webinfo from '@/mixins/webinfo.js'
export default {
  mixins: [webinfo],
  components: {
    Cropper: () => import('./cropper.vue'),
    SelectImgFromArticle: () => import('./selectImgFromArticle.vue'),
    SelectImgFromLibrary: () => import('./selectImgFromLibrary.vue'),
  },
  data() {
    return {
      imgUrl: '',
      fileName: '',
      content: '',
    }
  },
  props: ['defaultValue'],
  watch: {
    defaultValue: {
      immediate: true,
      handler(v) {
        if (v instanceof Object) {
          this.imgUrl = v.httpUrl
        } else {
          this.imgUrl = this.defaultCourseImg
        }
      },
    },
  },
  methods: {
    handleFileChange(e) {
      let file = e.target.files
      this.fileName = file[0].name
      if (!/\.(gif|jpg|jpeg|webp|png|GIF|JPG|PNG)$/.test(this.fileName)) {
        this.warnMsg('图片类型必须是.gif,jpeg,jpg,png.webp中的一种')
        this.fileName = ''
        return
      }
      var reader = new FileReader() //是一种异步文件读取
      reader.readAsDataURL(file[0]) //转换成base64 //数据读取完成触发
      reader.onload = (e) => {
        this.$bus.$emit('showCropperDialog', e.target.result)
      }
    },
    setImgInfo(v) {
      this.imgUrl = v
      this.upload()
    },
    setSelectImgInfo(v) {
      this.imgUrl = v
      //发送图片路径...
    },
    deleteImg() {
      this.imgUrl = this.defaultCourseImg
      this.$emit('e-emit', { id: '' })
    },
    //从正文选图片
    selectFromArticle() {
      this.$emit('fatherMethod')
      this.$bus.$emit('selectImgFromArticle', this.content)
    },
    //获取父组件正文内容
    getContent(val) {
      this.content = val
    },
    //从资源库选图片
    selectFromLibrary() {
      this.$bus.$emit('selectImgFromLibrary')
    },
    // 上传点击保存
    upload() {
      if (!this.imgUrl && this.imgUrl == '') return
      const optionImg = this.base64toFile(this.imgUrl)
      const formData = new FormData()
      formData.append('file', optionImg)
      tbSysAttachmentUpload(formData).then((res) => {
        let imgInfo = res.data.data[0]
        this.$emit('e-emit', imgInfo)
      })
    },
    base64toFile(dataurl) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let newFileName = this.fileName.split('.')
      newFileName = this.fileName.replace(
        newFileName[newFileName.length - 1],
        '',
      )
      return new File([u8arr], `${newFileName}${suffix}`, {
        type: mime,
      })
    },
  },
}
</script>
<style scoped lang="scss">
.img-cropper {
  position: relative;
  width: 210px;
  text-align: center;
  .img-box {
    width: 100%;
    height: 140px;
    border: 1px dashed #ccc;
    border-radius: 5px;
    padding: 6px;
    overflow: hidden;
    box-sizing: border-box;
    img {
      display: block;
      width: 100%;
      height: 100%;
      border-radius: 3px;
    }
  }
  .upload-btn {
    margin-top: 10px;
  }
}
</style>